package org.whh.org.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.whh.base.service.impl.BaseServiceImpl;
import org.whh.org.domain.Department;
import org.whh.org.mapper.DepartmentMapper;
import org.whh.org.service.IDepartmentService;

import java.util.Date;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;




    @Override
    public void insert(Department department) {
        department.setCreateTime(new Date());
        departmentMapper.insert(department);
        System.out.println("parentid");
        String path="";
        Department parent=department.getParent();
        if(parent.getId()!=0&&parent.getId()!=null){
            System.out.println("in");
            parent = departmentMapper.selectById(parent.getId());
            path = parent.getPath()+"/"+department.getId();
        }else {
            path = "/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    public void update(Department department) {
        System.out.println("update");
        System.out.println(department);

        department.setUpdateTime(new Date());
        String path = "";
        System.out.println(department.getParent().getId());
        if(department.getParent().getId()!=null&&department.getParent().getId()!=0){
            // 根据父部门的id，查询父部门的信息
            System.out.println("up");
            Department parent = departmentMapper.selectById(department.getParent().getId());
            // 父部门存在，该部门path = 父部门的path+"/"+自己的id
            path = parent.getPath()+"/"+department.getId();
        }else{
            // 父部门不存在，那么该部门的path=/自己的id
            path = "/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }



    @Override
    public List<Department> getTree() {
        List<Department> list=departmentMapper.getTree();

        System.out.println("list");
        System.out.println(list);
        return list;
    }
}
